<script setup>
import {get, post} from "../util/Request.js";
import {Toast} from "tdesign-mobile-vue";
import {ref, reactive, onMounted} from "vue";

const handleClick = () => {
  window.history.back(); // 返回上一级页面
};

const list = ref([]);

const form = reactive({
  bookName: '',
  author: '',
  category: '',
  description: '',
  publishDate: ''
});

function formatDate(date) {
  const d = new Date(date);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

function handleSubmit(event) {
  event.preventDefault();

  const data = {
    bookName: form.bookName,
    author: form.author,
    category: form.category,
    description: form.description,
    publishDate: formatDate(form.publishDate)
  };

  // 打印请求数据以便调试
  console.log('Request Data:', data);

  // 检查 category 是否有值
  if (!form.category) {
    Toast.fail('请选择一个分类');
    return;
  }

  post("/tbBook/addBook", data)
      .then(response => {
        if (response.code === 0) {
          Toast('提交成功');
        } else {
          Toast(r.data)
        }
      })
}

onMounted(() => {
  get("tbType/type").then(r => {
    if (r.code === 0) {
      list.value = r.data;
      // console.log('List data:', list.value); // 调试信息
    } else {
      // Toast(r.msg || '获取分类数据失败');
    }
  })
});
</script>

<template>
  <div>
    <t-navbar title="上架图书" :fixed="false" left-arrow @left-click="handleClick"/>
  </div>
  <form @submit="handleSubmit">
    <t-input v-model="form.bookName" name="bookName" label="书名" placeholder="请输入书名"/>
    <t-input v-model="form.author" name="author" label="作者" placeholder="请输入作者"/>
    <div style="margin-top: 3%">
      <label for="category" style="margin-left: -37%">类型</label>
      <select id="category" v-model="form.category" name="category" style="margin-left: 20%">
        <option value="" disabled selected>请选择分类</option>
        <option v-for="item in list" :key="item.id" :value="item.value">{{ item.label }}</option>
      </select>
    </div>
    <t-input v-model="form.description" name="description" label="图书简介" placeholder="请输入图书简介"/>
    <t-input v-model="form.publishDate" name="publishDate" type="date" label="出版时间" placeholder="请选择出版时间"/>
    <button type="submit">提交</button>
  </form>
</template>

<style scoped>
/* 你的样式 */
</style>
